package com.haibei.view.web;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.haibei.R;
import com.haibei.view.web.WuyouWebview.OnErrorListener;
import com.haibei.view.web.WuyouWebview.OnPageFinishedListener;
import com.haibei.view.web.WuyouWebview.OnPageStartListener;

/*
 * 具体业务层需要实现WebPage完成具体业务需要的webpage实例
 * @modify zhangfm
 * @author zhangy
 *
 */
public class WebPageClient extends BaseWebPageClient implements OnClickListener {
	private static final String TAG = "WebPageClient";
	private static final int TIME_OUT = 45000; // 超时45s
	private RequestLoadingWeb mRequestLoading;
	private String mLoadingTxt = null;
	private Context mContext = null;
	private WebActionCallBack mActionCallBack;

	private boolean mIsError;
	private boolean mIsClear = true;
	private boolean mIsReceiveError; // 是否触发过onReceiveError,用于处理网页加载出错时的一些判断

	public Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.WebPage.WEB_LOAD_TIMEOUT:
				Log.d(TAG, "web load timeout");
				if (mIsError) {
					handleWebError(true);
				}
				break;
			case Constant.WebPage.WEB_INVALID_SLEEP:
				loadWebToError();
				break;
			default:
				break;
			}
		}

	};

	public interface WebClientCallBack {

		WebResourceResponse getWebResource();

		void thirdLogin(int type, String url);
	}

	private WebClientCallBack mClientCallBack;

	/**
	 * 针对native和web加载通用一个loading框，此listener用于非网页加载失败时需要的操作
	 * 
	 */
	public interface OnNoWebLoadListener {
		void onNoWebLoad();
	}

	public void setWebClientCallBack(WebClientCallBack webClientCallBack) {
		mClientCallBack = webClientCallBack;
	}

	/**
	 * 加载出错时是否需要出现错误重试框
	 * 
	 * @param isClear
	 */
	public void setClear(boolean isClear) {
		mIsClear = isClear;
	}

	/**
	 * 设置加载中的文字
	 * 
	 * @param text
	 */
	public void setLoadingText(String text) {
		this.mLoadingTxt = text;
	}

	public WebPageClient(WuyouWebview webview, Context context, WebActionCallBack actionCallBack) {
		super(context, webview);
		initWebViewState();
		mIsError = true;
		mContext = context;
		mActionCallBack = actionCallBack;
	}

	/**
	 * 用于初始化,webView的状态
	 * 
	 * 设置WebChromeClient和WebViewClient对象
	 */
	public void initWebViewState() {
		mWebView.setWebChromeClient(mWebChromeClient);
		mWebView.setWebViewClient(mWebViewClient);
	}

	private WebViewClient mWebViewClient = new WebViewClient() {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d("WebPageClient", "--------------shouldOverrideUrlLoading----" + url);
			if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				mContext.startActivity(intent);
			}else
			{
				view.loadUrl(url);
			}
			return true;

		}
		@SuppressLint("NewApi")
		@Override
		public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
			Log.d(TAG, "--shouldInterceptRequest url=" + url);
			WebResourceResponse wrr = null;
			if (mClientCallBack != null) {
				wrr = mClientCallBack.getWebResource();
				if (wrr == null) {
					wrr = super.shouldInterceptRequest(view, url);
				}
			}
			return wrr;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d(TAG, "onPageStarted mRequestLoading = " + mRequestLoading + " ,url = " + url + "***");

			// if (!mIsReceiveError) {

			if (mWebView.getOnPageStartLinstener() != null) {
				mWebView.getOnPageStartLinstener().onPageStart(view);
			}

			mWebView.setUrl(url);
			// }
		}

		@Override
		public void onPageFinished(WebView view, String url) {

			Log.d(TAG, "onPageFinished url=" + url);

			String lat = SharePersistentUtils.getPerference(mContext, Constant.LocationConstant.LAT);
			String lon = SharePersistentUtils.getPerference(mContext, Constant.LocationConstant.LON);
			String cityCode = SharePersistentUtils.getPerference(mContext, Constant.LocationConstant.CITY_CODE);
			String cityName = SharePersistentUtils.getPerference(mContext, Constant.LocationConstant.CITY_NAME).replaceAll("市", "");

			mWebView.loadUrl("javascript:window.setGeolocation('" + lat + "," + lon + "','" + cityName + "','"
					+ cityCode + "')");
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			Log.d(TAG, "onLoadResource url = " + url + ",mRequestLoading = " + mRequestLoading);
			if (mWebView.getVisibility() == View.GONE && !url.startsWith("file:///android_asset/webkit/")) {
				mWebView.clearView();
				mWebView.setVisibility(View.VISIBLE);
			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			Log.d(TAG, "onReceivedError errorCode = " + errorCode + "," + description);
			mIsReceiveError = true;
			handleWebError(mIsClear);
			//mHandler.removeMessages(Constant.WebPage.WEB_LOAD_TIMEOUT);// 取消超时
		}

		/**
		 * onReceivedSslError为webView处理ssl证书设置,解决2.2版本webview不处理https请求，
		 * 页面显示空白的问题
		 */
		public void onReceivedSslError(WebView view, android.webkit.SslErrorHandler handler,
				android.net.http.SslError error) {
			handler.proceed();
		};
	};

	public void setErrorFlag(boolean error) {
		mIsError = error;
	}

	/**
	 * 判断url是否有效,主要防止url中含有//这样导致404的情况
	 * @param url
	 * @return
	 */
	public boolean isUrlValid(String url) {
		if (url == null)
			return false;
		if (url.startsWith("file:///"))
			return true;

		return true;
	}

	private void handlePageFinished(int status) {
		if (status == RequestLoadingWeb.STATUS_ERROR) {
			mWebView.setVisibility(View.GONE);
			mRequestLoading.statuesToError();
		} else {
			mWebView.setVisibility(View.VISIBLE);
			// 保存webview高度到cookie
			// CookiesManager.addWebViewHeightCookie(getContext(),
			// String.valueOf(mWebView.getMeasuredHeight()));
			/*
			 * if(getContext() instanceof MoreHelperActivity || mIsConsole){
			 * hideRequestLoading(); mIsConsole = false; }
			 */
			hideRequestLoading();
		}
	}

	/**
	 * 启动超时监听
	 */
	public void startTimeoutListen() {
		Message msg = mHandler.obtainMessage();
		msg.what = Constant.WebPage.WEB_LOAD_TIMEOUT;
		mHandler.removeMessages(Constant.WebPage.WEB_LOAD_TIMEOUT);
		boolean queenSuc = mHandler.sendMessageDelayed(msg, TIME_OUT);
		if (queenSuc) {
			Log.d(TAG, "timeout msg add queen successfull");
		}
	}

	/**
	 * 取消超时
	 */
	public void cancelTimeOut() {
		if (mHandler != null) {
			mHandler.removeMessages(Constant.WebPage.WEB_LOAD_TIMEOUT);
		}

	}

	/**
	 * 处理Webview的错误方法
	 * 
	 * @param clear
	 *            true:执行clearView等方法|false:仅仅stopLoading
	 */
	private void handleWebError(boolean clear) {
		Log.d(TAG, "handleWebError() clear = " + clear);
		mWebView.stopLoading();
		mWebView.contentLoadError();
		if (clear) {
			mWebView.clearView();
			loadWebToError();
		}
	}

	public void loadWebToError() {
		mWebView.stopLoading();
		mWebView.contentLoadError();
		mWebView.setVisibility(View.INVISIBLE);
		if (mRequestLoading != null) {
			mRequestLoading.statuesToError();
		}
	}

	private WebChromeClient mWebChromeClient = new WebChromeClient() {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			super.onProgressChanged(view, newProgress);
			mActionCallBack.setWebProgress(newProgress);
		}

		@Override
		public void onCloseWindow(WebView window) {
			super.onCloseWindow(window);
		}

		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			return super.onJsAlert(view, url, message, result);
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
			return super.onJsConfirm(view, url, message, result);
		}

		@Override
		public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
			return super.onJsPrompt(view, url, message, defaultValue, result);
		}

		@Override
		public void onConsoleMessage(String message, int lineNumber, String sourceID) {
			super.onConsoleMessage(message, lineNumber, sourceID);
			Log.d(TAG, "--onConsoleMessage message:" + message + ",lineNumber:" + lineNumber + ",sourceId:" + sourceID);
		}

	};

	/**
	 * 设置webview是否启动app cache
	 * 
	 * @param b
	 */
	public void openCache(boolean b) {
		if (b) {
			mWebSettings.setAppCacheEnabled(true);
			mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		} else {
			mWebSettings.setAppCacheEnabled(false);
			mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		}
	}

	/**
	 * 隐藏webview的垂直滚动条
	 */
	public void hideScrollBar() {
		mWebView.setVerticalScrollBarEnabled(false);
	}

	private void sleepWeb() {
		Message msg = mHandler.obtainMessage();
		msg.what = Constant.WebPage.WEB_INVALID_SLEEP;
		mHandler.sendMessageDelayed(msg, 500);

	}

	public RequestLoadingWeb getRequestLoading() {
		return mRequestLoading;
	}

	public void setRequestLoading(RequestLoadingWeb requestLoading) {
		this.mRequestLoading = requestLoading;
	}

	@Override
	public void showRequestLoading() {
		if (!TextUtils.isEmpty(mLoadingTxt)) {
			mRequestLoading.statuesToInLoading(mLoadingTxt);
		} else {
			mRequestLoading.statuesToInLoading(getContext().getResources().getString(R.string.request_loading_info));
		}

	}

	@Override
	public void hideRequestLoading() {
		mRequestLoading.statuesToNormal();
	}

	public void sendCookiByJS(String cookie) {
		Log.d("WebPageClient", "--home onPageFinished cookie=" + cookie);
		mWebView.loadUrl("javascript:$.common.set_global('" + cookie + "')");
	}

	public void setOnPageStartLinstener(OnPageStartListener onPageStartListener) {
		mWebView.setOnPageStartLinstener(onPageStartListener);
	}

	public void setPageOnFinishedListener(OnPageFinishedListener pageOnFinishedListener) {
		mWebView.setPageOnFinishedListener(pageOnFinishedListener);
	}

	public void setOnErrorListener(OnErrorListener errorListener) {
		mWebView.setOnErrorListener(errorListener);
	}

	/**
	 * WebView是不是处于加载中...
	 * 
	 * @return
	 */
	public boolean inLoading() {
		if (mRequestLoading.getStatus() == RequestLoadingWeb.STATUS_IN_LOADING)
			return true;
		return false;
	}

	public void setUrl(String url) {
		mWebView.setUrl(url);
	}

	public String getUrl() {
		return mWebView.getUrl();
	}

	public void stopLoading() {
		mWebView.stopLoading();
	}

	public void reload() {
		mWebView.reload();
	}

	@Override
	public void onClick(View v) {
	}

}
